package edu.msg.hrappy.backend.service.beans;

import edu.msg.hrappy.backend.model.Group;
import edu.msg.hrappy.backend.model.User;
import edu.msg.hrappy.backend.model.UserGroup;
import edu.msg.hrappy.backend.repository.GroupRepository;
import edu.msg.hrappy.backend.repository.UserRepository;
import edu.msg.hrappy.backend.repository.UserGroupRepository;
import edu.msg.hrappy.backend.repository.exception.RepositoryException;
import edu.msg.hrappy.backend.service.UserService;
import edu.msg.hrappy.backend.service.exception.ServiceException;
import edu.msg.hrappy.backend.service.util.Encryption;

import java.util.Collections;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class UserServiceBean implements UserService {

    @EJB
    private UserRepository userRepository;

    @EJB
    private UserGroupRepository      userGroupRepository;
    
    @EJB
    private GroupRepository      groupRepository;
    
    @Override
    public void insert(User obj) {

        try {
            obj.setPassword(Encryption.encrypt(obj.getPassword()));
            userRepository.insert (obj);
            User user = userRepository.getUserByUserName(obj.getUserName());
            Group group = groupRepository.getByName(user.getRoleInCompany());//user tipusu felhasznalo hozzaadasa
            UserGroup userGroup = new UserGroup(user,group);
            userGroupRepository.insert(userGroup);
        } catch (RepositoryException e) {
            throw new ServiceException("", e);
        }

    }

    @Override
    public void update(User obj) {
        try {
            userRepository.update(obj);
        } catch (RepositoryException e) {
            throw new ServiceException("", e);
        }

    }

    @Override
    public void delete(User obj) {
        try {
            userRepository.delete(obj);
        } catch (RepositoryException e) {
            throw new ServiceException("", e);
        }

    }

    @Override
    public List<User> getAll() {
        List<User> all = Collections.emptyList();
        try {
            all = userRepository.getAll();
        } catch (RepositoryException e) {
            throw new ServiceException("", e);
        }
        return all;
    }

    @Override
    public User getById(Long id) {
        User one;
        try {
            one = userRepository.getById(id);
        } catch (RepositoryException e) {
            throw new ServiceException("", e);
        }
        return one;
    }

	@Override
	public User getUserByUserName(String userName) {
		User one;
        try {
            one = userRepository.getUserByUserName(userName);
        } catch (RepositoryException e) {
            throw new ServiceException("", e);
        }
        return one;
    }

}
